<template>
    <el-drawer v-model="show" :title="title" size="70vw">
        <el-row>
            <el-col :span="24">
                <el-form ref="formRef" :model="formData" label-width="120" :rules="rules" v-loading="loading">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="所属区域" prop="areaCode">
                                        <el-select v-model="formData.areaCode" placeholder="请选择所属区域" style="width: 100%;">
                                            <el-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value"/>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <!-- <el-col :span="24">
                                    <el-form-item label="球员编码" prop="playerCode">
                                        <el-input v-model="formData.playerCode" placeholder="请输入球员编码" />
                                    </el-form-item>
                                </el-col> -->
                                <el-col :span="24">
                                    <el-form-item label="球员姓名" prop="playerName">
                                        <el-input v-model="formData.playerName" placeholder="请输入球员姓名" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="球员性别" prop="sex">
                                        <el-radio-group v-model="formData.sex">
                                            <el-radio-button label="男" value="M" />
                                            <el-radio-button label="女" value="F" />
                                        </el-radio-group>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="身份证号" prop="idCard">
                                        <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="头像" prop="photo">
                                <el-upload :limit="1" :show-file-list="false" :http-request="doUpload">
                                    <img v-if="formData.photo" :src="formData.photo" class="avatar" />
                                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="身高" prop="height">
                                <el-input type="number" v-model="formData.height" placeholder="请输入身高">
                                    <template #append>cm</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="体重" prop="weight">
                                <el-input type="number" v-model="formData.weight" placeholder="请输入体重">
                                    <template #append>kg</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="年龄" prop="age">
                                <el-input v-model="formData.age" placeholder="请输入年龄"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="生日" prop="birth">
                                 <el-date-picker v-model="formData.birth" type="date" placeholder="请选择生日" :disabled-date="disabledDate" style="width: 100%;" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-col>
        </el-row>
        <template #footer>
            <div class="footer-row">
                <el-button type="primary" @click="preSave" :loading="loading">保存</el-button>
                <el-button @click="closeDrawer" :loading="loading">关闭</el-button>
            </div>
        </template>
    </el-drawer>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { usePlayerStore } from '../../../store/player'
import { usePickerStore } from '../../../store/picker'
import { uploadFile } from '../../../api/common'
import type { FormInstance } from 'element-plus'
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus'

const playerStore = usePlayerStore()
const pickerStore = usePickerStore()

const props = defineProps({
  show: Boolean,
  detailData: Object
})
const emit = defineEmits(['update:show', 'close'])

const show = computed<boolean>({
  get: () => props.show,
  set: val => emit('update:show', val)
})
const formRef = ref<FormInstance>()
const rules = {
    areaCode:[
        { required: true, message: '请选择所属区域', trigger: 'blur' },
    ],
    playerCode: [
        { required: true, message: '请输入球员编码', trigger: 'blur' },
    ],
    playerName: [
        { required: true, message: '请输入球员姓名', trigger: 'blur' },
    ],
    sex:[
        { required: true, message: '请选择球员性别', trigger: 'blur' },
    ],
    idCard:[
        { required: false, message: '请输入身份证号', trigger: 'blur' },
    ],
    photo:[
        { required: true, message: '请上传头像', trigger: 'blur' },
    ],
}
const title = ref<string>('');
const loading = ref<boolean>(false);
const formData = ref<any>({});

const areaList = ref<any>([])
watch(() => props.detailData, () => {
    loading.value = false
    initData()
},{deep: true})
watch(() => show, () => {
    if (!show.value) {
        emit('close')
    }
}, {deep: true})
onMounted(() => {
    getAreaList()
})
function closeDrawer() {
    show.value = false
}
function getAreaList() {
    pickerStore.getAreaList({}).then((res) => {
        if (res.code === 't_200') {
            areaList.value = res.obj
        }
    })
}
function initData() {
    let data = {...props.detailData || {}}
    if (data.id){
        title.value = '编辑球员'
        formData.value = {
            areaCode: data.areaCode,
            playerCode: data.playerCode,
            playerName: data.playerName,
            photo: data.photo,
            sex: data.sex,
            idCard: data.idCard,
            birth: data.birth,
            height: data.height,
            weight: data.weight,
            age: data.age,
        }
    } else {
        title.value = '新增球员'
        formData.value = {}
    }
}
function disabledDate (time: Date) {
  return time.getTime() > Date.now()
}
function doUpload(obj:any) {
    let params = {
        file: obj.file
    }
    uploadFile(params).then((res:any) => { 
        if (res.code === 't_200') {
            formData.value.photo = res.obj
        } else {
            ElMessage.error(res.msg)
        }
    })
}
function preSave() {
    formRef.value?.validate((valid) => {
        if (valid) {
            doSave()
        }
    })
}

function doSave() {
    loading.value = true
    let detailData = {...props.detailData || {}}
    let data = {...formData.value}
    if (data.birth) {
        data.birth = dayjs(data.birth).format('YYYY-MM-DD')
    }
    let params = {
        id: detailData.id || '',
        areaCode: data.areaCode,
        playerCode: data.playerCode,
        playerName: data.playerName,
        photo: data.photo,
        sex: data.sex,
        idCard: data.idCard,
        birth: data.birth,
        height: data.height,
        weight: data.weight,
        age: data.age,
    }
    playerStore.savePlayer(params).then((res) => {
        if (res.code === 't_200') {
            ElMessage.success('保存成功！')
            closeDrawer()
        } else {
            ElMessage.error(res.msg)
        }
    }).catch(() => {
        ElMessage.error("网络异常")
    }).finally(() => {
        loading.value = false
    })
}
</script>
<style lang="scss" scoped>
.avatar-uploader-icon{
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  text-align: center;
}
.footer-row{
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
</style>
